from datetime import datetime
from typing import Optional
from enum import Enum
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum as SQLEnum, Boolean
from sqlalchemy.orm import relationship
from pydantic import BaseModel, Field

from backend.core.database import Base


class MeetingStatus(str, Enum):
    """会议状态枚举类"""
    CREATED = "created"  # 已创建
    UPLOADING = "uploading"  # 上传中
    UPLOADED = "uploaded"  # 上传完成
    TRANSCRIBING = "transcribing"  # 转录中
    TRANSCRIBED = "transcribed"  # 转录完成
    SUMMARIZING = "summarizing"  # 总结中
    SUMMARIZED = "summarized"  # 总结完成
    FAILED = "failed"  # 处理失败


class Meeting(Base):
    """会议数据库模型"""
    __tablename__ = "meetings"
    
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(200), nullable=False, index=True)
    description = Column(Text, nullable=True)
    created_by = Column(Integer, ForeignKey("users.id"), nullable=False)
    
    # 文件相关信息
    audio_file_path = Column(String(500), nullable=True)  # 音频文件路径
    audio_file_size = Column(Integer, nullable=True)  # 音频文件大小
    audio_duration = Column(Float, nullable=True)  # 音频时长（秒）
    
    # 状态信息
    status = Column(SQLEnum(MeetingStatus), default=MeetingStatus.CREATED, nullable=False)
    is_processed = Column(Boolean, default=False, nullable=False)
    
    # 时间信息
    created_at = Column(DateTime, default=datetime.now, nullable=False)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now, nullable=False)
    completed_at = Column(DateTime, nullable=True)
    
    # 转录结果信息
    transcription_text = Column(Text, nullable=True)  # 完整转录文本
    transcription_segments = Column(Text, nullable=True)  # 转录片段（JSON格式）
    
    # 总结信息
    summary_text = Column(Text, nullable=True)  # 总结文本
    
    # 关联关系
    user = relationship("User", back_populates="meetings")
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            "id": self.id,
            "title": self.title,
            "description": self.description,
            "created_by": self.created_by,
            "audio_file_path": self.audio_file_path,
            "audio_file_size": self.audio_file_size,
            "audio_duration": self.audio_duration,
            "status": self.status,
            "is_processed": self.is_processed,
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
            "completed_at": self.completed_at.isoformat() if self.completed_at else None,
            "transcription_text": self.transcription_text,
            "summary_text": self.summary_text
        }


# Pydantic模型
class MeetingCreate(BaseModel):
    """创建会议请求模型"""
    title: str = Field(..., max_length=200, description="会议标题")
    description: Optional[str] = Field(None, description="会议描述")


class MeetingResponse(BaseModel):
    """会议响应模型"""
    id: int
    title: str
    description: Optional[str]
    status: MeetingStatus
    created_at: str
    updated_at: Optional[str]
    
    class Config:
        from_attributes = True


class MeetingDetailResponse(BaseModel):
    """会议详细响应模型"""
    id: int
    title: str
    description: Optional[str]
    created_by: int
    audio_file_path: Optional[str]
    status: MeetingStatus
    is_processed: bool
    created_at: str
    updated_at: str
    completed_at: Optional[str]
    transcription_text: Optional[str]
    summary_text: Optional[str]
    
    class Config:
        from_attributes = True


class MeetingUpdate(BaseModel):
    """更新会议请求模型"""
    title: Optional[str] = Field(None, max_length=200, description="会议标题")
    description: Optional[str] = Field(None, description="会议描述")
    status: Optional[MeetingStatus] = Field(None, description="会议状态")